package com.faf.ui;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.faf.bean.Orders;
import com.faf.bean.SalesDetails;
import com.faf.dao.AccessDao;
import com.faf.dao.OrdersDao;
import com.faf.dao.SalesDetailsDao;
import com.faf.dao.impl.AccessDaoImpl;
import com.faf.dao.impl.OrdersDaoImpl;
import com.faf.dao.impl.SalesDetailsDaoImpl;
import com.faf.tools.GetDate;

import net.sf.json.JSONArray;

/**
 * Servlet implementation class StoreSalesDetails
 */
@WebServlet("/StoreSalesDetails")
public class StoreSalesDetails extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public StoreSalesDetails() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置请求的编码格式
		request.setCharacterEncoding("utf-8");
		//设置响应的编码格式
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		int storeId = 0;
		try
		{
			storeId = (int) request.getSession().getAttribute("storeId");
			if(request.getParameter("salesDetails") != null) {
				if("1".equals(request.getParameter("salesDetails"))) {
					SalesDetailsDao saleDetailsDao = new SalesDetailsDaoImpl();
					Calendar cal = Calendar.getInstance();
					//获得当前年份
					String year = cal.get(Calendar.YEAR)+"";
					//获得当前月份
					String nowMonth = cal.get(Calendar.MONTH)+1+"";
					System.out.println("当前年份："+year);
					System.out.println("当前月份："+nowMonth);
					//每一个月的成交量数组
					String[][] saledetail = new String[12][2];
					for(int i = 0; i < 12; i++) {
						saledetail[i][0] = 0+"";
						saledetail[i][1] = year;
					}
					//获得某商家的全部订单
					List<Orders> ordersList = null;
					OrdersDao ordersDao = new OrdersDaoImpl();
					ordersList = ordersDao.getOrderListBystoreIdAndOrdersState(storeId, 3, year);
					//根据订单月对订单进行分类，最后得到每个月的成交量
					GetDate getDate = new GetDate();
					for(int i = 0; i < ordersList.size(); i++) {
						String[] date = getDate.getYearAndMonthAndDay(ordersList.get(i).getOrdersTime());
						for(int n = 1; n <= 12; n++) {
							String month = n+"";
							if(month.equals(date[1])) {
								int SaleVolume = 0;
								//System.out.println(saledetail[n-1][0]);
								SaleVolume = Integer.parseInt(saledetail[n-1][0]) + 1;
								saledetail[n-1][0] = SaleVolume+"";
							}
						}
					}
					//遍历成交量数组，如果年和月同时不存在时，进行插入操作，否则修改已有成交量,1:修改,2:插入
					for(int i = 1; i <= saledetail.length; i++) {
						if(saledetail[i-1][0] != "0") {
							if(saleDetailsDao.judgeYearAndMonth(i+"", year) == 1) {
								saleDetailsDao.insertOrAlterTurnover(storeId, Double.parseDouble(saledetail[i-1][0]), i+"", year, 1+"");
							}else {
								saleDetailsDao.insertOrAlterTurnover(storeId, Double.parseDouble(saledetail[i-1][0]), i+"", year, 2+"");
							}
						}
					}
					//计算当前月的访问量，并存入数据库
					AccessDao accessDao = new AccessDaoImpl();
					DateFormat dateFromat = DateFormat.getDateInstance();
						try{
							Date d = dateFromat.parse(year + "-"+ nowMonth +"-1");
							long milliseconds = d.getTime();
							long pv = accessDao.getAccessByStoreId_TimeStamp_After(storeId, milliseconds);
							//判断saledetails中有无该年月的记录，若有则修改该记录的pv，若无则插入该记录。
							if(saleDetailsDao.judgeYearAndMonth(nowMonth, year) == 1) {
								saleDetailsDao.insertOrAlterPV(storeId, pv, nowMonth, year, 1+"");
							}else {
								saleDetailsDao.insertOrAlterPV(storeId, pv, nowMonth, year, 2+"");
							}
					
						}catch (Exception e){
						e.printStackTrace();
						} 
					
					List<SalesDetails> SalesDetailsList = saleDetailsDao.getSalesDetailsList(storeId,year);
					JSONArray SalesDetails = JSONArray.fromObject(SalesDetailsList);
					out.print(SalesDetails);
				}
			}
		} catch (Exception e)
		{
			out.print(e);
			e.printStackTrace();
		}
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		doGet(request, response);
	}
	
	private void forward(HttpServletRequest request, HttpServletResponse response, String url, Object... objs) throws ServletException, IOException {
		for (int i = 0; i < objs.length; i+=2)
		{
			request.setAttribute(objs[i]+"", objs[i+1]);
		}
		
		RequestDispatcher rd = request.getRequestDispatcher(url);
		rd.forward(request, response);
	}

}
